﻿using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Grpc.Net.ClientFactory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NetTaste;
using SharedKernel.Infrastructure.Grpc.Interceptors;
using SharedKernel.Infrastructure.Grpc.Options;
using SharedKernel.Infrastructure.Redis;
using System.IO.Compression;
using static System.Net.WebRequestMethods;

namespace SharedKernel.Infrastructure.Grpc
{
    /// <summary>
    /// Grpc客户端初始化
    /// </summary>
    public static class GrpcClientDependencyInjection
    {
        /// <summary>
        /// 注入Grpc客户端
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <param name="serviceName">Grpc服务名称</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection InjectGrpcClient<TClient>(this IServiceCollection services, IConfiguration configuration, string serviceName) where TClient : class
        {
            // 注册配置
            var grpcOptions = configuration.GetSection($"GrpcClients:{serviceName}").Get<GrpcClientOptions>(); 
            services.AddTransient<GrpcClientAuthorizationInterceptor>();
            if (grpcOptions != null)
            { 
                //Grpc默认是瞬时注入
                services.AddGrpcClient<TClient>(o =>
                {
                    o.Address = new Uri(grpcOptions.Address); 
                }).AddInterceptor<GrpcClientAuthorizationInterceptor>()
                .ConfigureHttpClient(httpCilent =>
                {
                    //这里加入自定义的鉴权码
                    httpCilent.DefaultRequestHeaders.Add("servicename", serviceName);
                    httpCilent.DefaultRequestHeaders.Add("authorizationcode", grpcOptions.AuthorizationCode);
                     
                }).ConfigureChannel(channelOptions =>
                {
                    //最大重试次数
                    channelOptions.MaxRetryAttempts = grpcOptions.MaxRetryCount;
                }).ConfigureHttpClient(httpClient =>
                {

                })
                //开启取消调用（客户端调用时候设置deadline属性，超过时间则报错）
                .EnableCallContextPropagation(t => t.SuppressContextNotFoundErrors=true);
            }
            return services;
        }
    }
}
